package com.itobase.questionnaire.config.auth;

import com.itobase.questionnaire.model.Admin;
import com.itobase.questionnaire.model.auth.User;

import com.itobase.questionnaire.util.Message;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;


/**
 * @author liucong
 * @date 2018/7/26
 */

@Aspect
@Component
public class AuthAOP {

    @Around("execution(* com.itobase.questionnaire.controller..*.*(..)) && !execution(* com.itobase.questionnaire.controller.LoginController.*(..))")
    Object checkLogin(ProceedingJoinPoint joinPoint) throws Throwable {
        Object[] args = joinPoint.getArgs();
            Subject subject = SecurityUtils.getSubject();


            User user = (User) subject.getPrincipal();
            if (user != null && user.getUsername() != null) {
                return joinPoint.proceed(args);
            } else {
                return Message.createErr("请先登录！");
        }
    }

    @Around("execution(* com.itobase.questionnaire.controller..*.*(..)) &&" +
            "!execution(* com.itobase.questionnaire.controller.LoginController.*(..)) &&" +
            "!execution(* com.itobase.questionnaire.controller.ClientController.*(..)) &&" +
            "!execution(* com.itobase.questionnaire.controller.UserController.*(..)) &&" +
            "!execution(* com.itobase.questionnaire.controller.SubmissionController.*(..))")
    Object checkAdmin(ProceedingJoinPoint joinPoint) throws Throwable {
        Object[] args = joinPoint.getArgs();
        Subject subject = SecurityUtils.getSubject();
        User user = (User) subject.getPrincipal();
        if(user instanceof Admin){
            return joinPoint.proceed(args);
        }else{
            return Message.createErr("权限不足，请使用管理员账号登录");
        }
    }
}
